package com.master5.grocerylist.deprecated;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.master5.grocerylist.ConnectionHelper;
import com.master5.grocerylist.Dao;


public class EmployeeDao extends Dao<Employee> {
	public List<Employee> findAll() {
        List<Employee> list = new ArrayList<Employee>();
        Connection c = null;
    	String sql = "SELECT * FROM employee ORDER BY employee_id";
        try {
            c = ConnectionHelper.getConnection();
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()) {
                list.add(ParseObject(rs));
            }
        } catch (SQLException e) {
        	e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
			ConnectionHelper.close(c);
		}
        return list;
    }
	
	public Employee findById(int id) {
		Connection c = null;
		String sql = "SELECT * FROM employee WHERE employee_id = ?";
		Employee emp = null;
		try {
			c = ConnectionHelper.getConnection();
			PreparedStatement s = c.prepareStatement(sql);
			s.setInt(1, id);
			ResultSet rs = s.executeQuery();
			
			if (!rs.next())
				return null;
			
			emp = ParseObject(rs);
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionHelper.close(c);
		}
		
		return emp;
	}

	public boolean createEmployee(String name, String email, int salary) {
		Connection c = null;
		String sql = "INSERT INTO employee(employee_name, employee_email, employee_salary) VALUES(?, ?, ?)";
		try {
			c = ConnectionHelper.getConnection();
			PreparedStatement s = c.prepareStatement(sql);
			s.setString(1, name);
			s.setString(2, email);
			s.setInt(3, salary);
			s.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			ConnectionHelper.close(c);
		}
		
		return true;
	}
	
	@Override
	protected Employee ParseObject(ResultSet rs) throws SQLException {
		Employee employee = new Employee();
		employee.setId(rs.getInt("employee_id"));
		employee.setName(rs.getString("employee_name"));
		employee.setEmail(rs.getString("employee_email"));
		employee.setSalary(rs.getInt("employee_salary"));
        return employee;
	}
}
